require "digest/sha1"

class User < ActiveRecord::Base
  validates_presence_of :email
  
  validates_format_of   :email, 
                        :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                        :message => 'address must be in a valid format [user@domain.com]'
  
  validates_uniqueness_of :email,
                          :message => 'address already exists'
                          
  attr_accessor :password, :confirm_password
  
  # Overrides hashed_password accessor so that when hashed_password is set to 
  # the users password, it hashes it using the seed, and the password
  
  def hashed_password=(password)
    write_attribute(:hashed_password, Digest::SHA1.hexdigest(self.hash_seed + password))
  end
  
  def before_validation
    self.email = self.email.clean_string if self.email
  end
  
  def validate_on_create
    errors.add(:confirm_password, "must match password") unless !password || password == confirm_password
    errors.add(:password, "cannot be blank") unless !password || password.length > 0
  end
  
  def before_create
    self.hash_seed = String.generate_random
    self.hashed_password = self.password
  end
  
  # Let's remove those nasty passwords that are stored in plain text in memory..
  # we certainly don't want those available to anyone.
  def after_create
    @password = nil
    @confirm_password = nil
  end
end
